/*
 * =====================================================================================
 *
 *       Filename:  logs_search_request.cc
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2013年07月03日 18时58分20秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Xie Yanping (), 
 *        Company:  www.Qihoo.net
 *
 * =====================================================================================
 */

#include "logs_search_request.h"

#include <string>
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include "base/logging.h"
#include "results_in_database.h"

namespace imserver {
namespace fcgi {

bool LogsSearchRequest::Response() {
  LOG_DEBUG("AddFriendRequest::Response called." << body_);
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }

  std::string rsp_header("Content-type: text/html; charset=utf-8\r\n\r\n");
  FCGX_PutS(rsp_header.c_str(), fcgi_out_);

  std::string date = GetPostArg("date");
  ::imlogs::ResultsInDatabase::DialogueArray dialogue_array;
  ::imlogs::ResultsInDatabase::GetInst().GetBreakStatistics(&dialogue_array, date);
  std::string rsp_body("{root:[");
  boost::format dialogue_format("{\"sender\":%1%,\"receiver\":%2%,\"time\":%3%,\"count\":%4%}");
  int index = 0, message_count = 0;
  BOOST_FOREACH(const ::imlogs::ResultsInDatabase::DialogueData& dialogue_data, dialogue_array) {
    if (index++ > 0)
      rsp_body.append(",");

    dialogue_format % dialogue_data.sender_ % dialogue_data.receiver_ % dialogue_data.time_ % dialogue_data.count_;
    rsp_body.append(dialogue_format.str());
    message_count += dialogue_data.count_;
  }

  rsp_body.append(boost::str(boost::format("], count: %1%}") % message_count));
  FCGX_PutS(rsp_body.c_str(), fcgi_out_);

  return true;
}

}
}


